/*!
 @header RegisterPersonBaseInfoViewController.m
 @author 周益
 @version 1.0.0 2013/01/28 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */


#import "RegisterPersonBaseInfoViewController.h"
#import "Helper.h"
#import "Config.h"
#import "RegisterRealNameFormViewController.h"
#import "CollageTextField.h"
#import "ProvincePickerViewController.h"
#import "Collage.h"

#define AREA_TEMPLATE @"    <font size=18>地区</font>    <font size=15 color='gray'>%@</font>"

//  -业务逻辑细节说明-
//
//  @abstract       头像选择提供两种方法，拍照和从相册里面选，但如果设备不支持拍照，那么就会使用相册。头像选择成功后会根据比例和大小对其压缩。
//
//  @discussion

//  @notes          变量_canChangeImageBg判断是否可以改变头像背景,因为用户编辑了头像后，就不再需要显示默认的。
//                 值为true时，表示可以修改头像的默认背景，否则不可以修改。


//  -类修改日志-
//  修改人   修改时间      针对版本         修改描述

//  周益    2013-4-9      1.2.1       新增填写地区功能


@interface RegisterPersonBaseInfoViewController ()<UITextFieldDelegate>

@end

@implementation RegisterPersonBaseInfoViewController
@synthesize avatar = _avatar;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = _L(@"vc_title_057");
    
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;

    _canChangeImageBg = YES;

    //导航按钮：返回
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //头像
    _genderImageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 20, 220, 211)];
    [_genderImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"user_btn_002@2x" ofType:@"png"]]];
    [self.view addSubview:_genderImageView];
    _genderImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGestureLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(genderImageViewEvent:)];
    [_genderImageView addGestureRecognizer:tapGestureLabel];
    
    //男性按钮
    _manButton = [[UIButton alloc] initWithFrame:CGRectMake(50, 240, 95, 36.5)];
    _manButton.tag = 1;
    [_manButton setImage:[UIImage imageNamed:@"user_btn_003"] forState:UIControlStateNormal];
    [_manButton setImage:[UIImage imageNamed:@"user_btn_004"] forState:UIControlStateSelected];
    [_manButton addTarget:self action:@selector(genderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_manButton];
    
    //女性按钮
    _womanButton = [[UIButton alloc] initWithFrame:CGRectMake(170, 240, 95, 36.5)];
    _womanButton.tag = 2;
    [_womanButton setImage:[UIImage imageNamed:@"user_btn_005"] forState:UIControlStateNormal];
    [_womanButton setImage:[UIImage imageNamed:@"user_btn_006"] forState:UIControlStateSelected];
    [_womanButton addTarget:self action:@selector(genderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_womanButton];
    
    //地区框
    //校园生活圈个性化处
    if ([_CONFIG_APP_KEY isEqualToString:@"XYSHQ"]) {
        
        CollageTextField *college = [[CollageTextField alloc] initWithFrame:CGRectMake(40.0f, 290.0f, 240.0f, 40.0f)];
        college.tag = 100;
        college.delegate = self;
        [self.view addSubview:college];
        
    }
    else {
        
        UIImageView *areaView = [[UIImageView alloc] initWithFrame:CGRectMake(50.0f, 290.0f, 220.0f, 40.0f)];
        areaView.image = [UIImage imageNamed:@"com_bg_010"];
        [self.view addSubview:areaView];
        
        _areaLabel = [[RTLabel alloc] initWithFrame:CGRectMake(50.0f, 300.0f, 220.0f, 30.0f)];
        _areaLabel.text = [NSString stringWithFormat:AREA_TEMPLATE, @""];
        
        _areaLabel.lineSpacing = 10.0f;
        [self.view addSubview:_areaLabel];
        
        UITapGestureRecognizer *tapGestureRTLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(areaLabelEvent:)];
        [_genderImageView addGestureRecognizer:tapGestureLabel];
        [_areaLabel addGestureRecognizer:tapGestureRTLabel];
    }
    
    //下一步按钮
    UIButton *nextButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 350, 300, 44)];
    [nextButton setBackgroundImage:[UIImage imageNamed:@"com_btn_006_n"] forState:UIControlStateNormal];
    [nextButton setTitle:_L(@"btn_yes_11") forState:UIControlStateNormal];   //下一步
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextButton.titleLabel.font = _SYS_FONT_009;
    [nextButton addTarget:self action:@selector(nextButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*!
 @abstract 头像图片点击事件
 */
- (void)genderImageViewEvent:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
                                                             delegate:self
                                                    cancelButtonTitle:_L(@"btn_no_01")
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:_L(@"btn_photo_01"), _L(@"btn_photo_02"), nil];
    
    [actionSheet showInView:self.view];
}

- (void)areaLabelEvent:(id)sender
{
//    _customPickerView = [[CustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
//    _customPickerView.delegate = self;
//    _customPickerView.areaPickerOption = 1;
//    [self.view addSubview:_customPickerView];
//    
//    _customPickerView.location = _area;
//    [_customPickerView pickerShow:HZAreaPickerViewType];
    _customPickerView = [[UICustomPickerView alloc] initWithFrame:CGRectMake(0,_SYS_FRAME_HEIGHT - 260-44, 320, 260)];
    _customPickerView.delegate = self;
    _customPickerView.location = _area;
    _customPickerView.hzAreaPickerStyle = HZAreaPickerWithStateAndCityAndDistrict;
    _customPickerView.areaPickerOption = HZAreaPickerInitNormalOption;
    [self.view addSubview:_customPickerView];
    
    [_customPickerView pickerShow:UICustomPickerViewAreaType];
}

/*!
 @abstract 性别按钮事件
 */
- (void)genderButtonEvent:(id)sender
{
    //用户点击一次性别按钮
    _isGenderButtonChanged = YES;
    
    UIButton *button = (UIButton *)sender;
    if (button.tag == 1) {
        [_manButton setSelected:YES];
        [_womanButton setSelected:NO];
    }else if (button.tag == 2) {
        [_manButton setSelected:NO];
        [_womanButton setSelected:YES];
    }
    
    //先判断是否可以改变头像背景,因为用户编辑了头像后，就不再需要显示默认的
    if (_canChangeImageBg) {
        if ([_manButton isSelected]) {
            [_genderImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"user_btn_002@2x" ofType:@"png"]]];
        }else{
            [_genderImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"user_btn_001@2x" ofType:@"png"]]];
        }
    }
}

/*!
 @abstract 下一步按钮事件
 */
- (void)nextButtonEvent:(id)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:[_manButton isSelected] forKey:@"sex"];

    //用户操作判断
    if (_isGenderImageChanged && !_isGenderButtonChanged) {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_34")];   //请设置性别
        
    }else if (!_isGenderImageChanged && _isGenderButtonChanged){
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_35")];   //请设置头像
        
    }else if (!_isGenderButtonChanged && !_isGenderImageChanged){
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_36")];   //请设置头像和性别
        
    }else if (![_CONFIG_APP_KEY isEqualToString:@"XYSHQ"] &&
              (_area == nil ||
               [@"" isEqualToString:_area] ||
               [@"(null)" isEqualToString:_area]))
    {
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_37")];   //请选择地区
        
    }else if ([_CONFIG_APP_KEY isEqualToString:@"XYSHQ"] &&
              ((UITextField *)[self.view viewWithTag:100]).text.length == 0
              )
    {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_137")];
    }
    
    else{
        
        RegisterRealNameFormViewController *realNameVC = [[RegisterRealNameFormViewController alloc] init];
        realNameVC.avatar = _avatar;
        realNameVC.area = _area;
        
        if ([_CONFIG_APP_KEY isEqualToString:@"XYSHQ"]) {
            realNameVC.collage = ((UITextField *)[self.view viewWithTag:100]).text;
        }
        
        [self.navigationController pushViewController:realNameVC animated:YES];
    }
    
}

/*!
 @abstract 裁剪图片
 @param image 需要裁剪的图片
 */
- (void)cropImage:(UIImage *)image
{
    //获得图片后，进行裁剪
    GKImageCropper* cropper = [[GKImageCropper alloc] init];
    cropper.delegate = self;
    cropper.image = image;
    cropper.cropSize = CGSizeMake(320, 320);
    cropper.rescaleImage = NO;
    cropper.rescaleFactor = 1.0;
    cropper.dismissAnimated = YES;
    
    [self presentModalViewController:cropper animated:YES];
}


#pragma mark - GKImageCropper Delegate

- (void)imageCropperDidFinish:(GKImageCropper *)imageCropper withImage:(UIImage *)image {
    
    UIImage* newImage = [Helper resizeImage:image forStyle:PictureStyleAvart];
    NSData* data = [Helper compressImageData:newImage withStyle:PictureStyleAvart];
    _avatar = [UIImage imageWithData:data];
    
    _genderImageView.image = image;
    _isGenderImageChanged = true;
}

#pragma mark - UIImagePickerControllerDelegate

// 系统图片拾取协议方法
//
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    _canChangeImageBg = NO;
    [picker dismissModalViewControllerAnimated:YES];
    
    UIImage *image;
    
    //判断picker是否是可编辑相片的，如果picker为可编辑则获取编辑后的image，否则获取原始的image
    if (picker.isEditing) {
        
        image = [info objectForKey:UIImagePickerControllerEditedImage];
    }else{
        
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    [Helper showAllTextDialog:_L(@"title_loading_01") inSeconds:1];
    [self performSelector:@selector(cropImage:)
               withObject:image
               afterDelay:1];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.delegate = self;
    //拍照模式
    if (buttonIndex == 0) {
        
        //判断摄像头是否可用
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }else{
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        [self presentModalViewController:imagePicker animated:YES];
        
        //访问相册模式
    }else if (buttonIndex == 1){
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.allowsEditing = NO;
        [self presentModalViewController:imagePicker animated:YES];
    }
}

#pragma mark - CustomPickerView Delegate

- (void)customPickerView:(UICustomPickerView *)customPickerView areaStringReceived:(NSString *)area
{
    _area = area;
    _areaLabel.text = [NSString stringWithFormat:AREA_TEMPLATE, area];
}

#pragma mark - UITextField Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fillCollage:) name:@"fill_collage" object:nil];
    
    ProvincePickerViewController *provincePickerVC = [[ProvincePickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
    
    UITextField *collageTextField = (UITextField *)[self.view viewWithTag:100];
    
    if ([[collageTextField text] length] != 0 &&
        [[[collageTextField text] componentsSeparatedByString:@" "] count] > 1
        ) {
        provincePickerVC.selectedCollageName = [[collageTextField text] componentsSeparatedByString:@" "][1];
    }
    
    UINavigationController *provincePickerNC = [[UINavigationController alloc] initWithRootViewController:provincePickerVC];
    [Helper navigationControllerCommonStyle:provincePickerNC];
    [self.navigationController presentModalViewController:provincePickerNC animated:YES];
    return NO;
    
}

- (void)fillCollage:(NSNotification *)notification
{
    UITextField *collageTextField = (UITextField *)[self.view viewWithTag:100];
    Collage *collage = (Collage *)notification.object;
    if (collage != nil) {
        collageTextField.text = [NSString stringWithFormat:@"%@ %@",collage.region, collage.name];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"fill_collage" object:nil];
}
@end
